/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.spring.event.blocking;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.pajamas.starter.core.util.StreamOptUtils;
import org.pajamas.starter.integration.spring.event.AbstractPropertyChangedEventHandler;

import java.util.Collections;
import java.util.EventObject;
import java.util.Set;

/**
 * @author william
 * @since 2024/3/29
 */
public abstract class IteratorPropertyChangedEventHandler<P, K> extends AbstractPropertyChangedEventHandler {
    protected IteratorPropertyChangedEventHandler(String propertyKey, boolean skipInitializing) {
        super(propertyKey, skipInitializing);
    }

    protected abstract Set<P> getUnchangedProperty();

    protected abstract Set<P> getChangedProperty();

    protected abstract K keyExtractor(P property);

    protected abstract void increase(Set<P> property);

    protected abstract void decrease(Set<P> property);

    @Override
    public void handle(EventObject eventObject) {
        Set<P> changedProperty = ObjectUtils.firstNonNull(this.getChangedProperty(), Collections.emptySet());
        Set<P> unchangedProperty = ObjectUtils.firstNonNull(this.getUnchangedProperty(), Collections.emptySet());

        Set<P> increasing = StreamOptUtils.Filtering.difference(changedProperty, unchangedProperty, this::keyExtractor);
        Set<P> decreasing = StreamOptUtils.Filtering.difference(unchangedProperty, changedProperty, this::keyExtractor);

        if (CollectionUtils.isNotEmpty(increasing)) {
            this.increase(increasing);
        }
        if (CollectionUtils.isNotEmpty(decreasing)) {
            this.decrease(decreasing);
        }
    }
}
